﻿using CNI.Repostitory.Interface;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace CNI.Repository.Table
{
    internal class Entity<T> : TableEntity
    {
        public Entity(T data, string PartionKeyPropertyName, string RowKeyValue)
        {
            this.PartitionKey = data.GetType().GetProperty(PartionKeyPropertyName).GetValue(data).ToString();
            this.RowKey = RowKeyValue;
            this.Data = JsonConvert.SerializeObject(data);
        }
        public string Data { get; set; }
    }

    public class TableIngestion<T> : IIngestRepository<T>
    {
        private CloudStorageAccount cloudStorageAccount = null;
        private CloudTable cloudTable = null;
        private string tableName = null;
        private string partionKeyName = null;

        // Constructor
        public TableIngestion(
            CloudStorageAccount Account,
            string TableName,
            string PartionKeyName)
        {
            this.cloudStorageAccount = Account;
            this.tableName = TableName;
            this.cloudTable = cloudStorageAccount.CreateCloudTableClient().GetTableReference(tableName);
            this.cloudTable.CreateIfNotExists();

            this.partionKeyName = PartionKeyName;
        }

        public void Ingest(T Data)
        {
            var entity = new Entity<T>(
                Data,
                this.partionKeyName,
                (DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks).ToString());
            TableOperation insertOperation = TableOperation.InsertOrReplace(entity);
            cloudTable.Execute(insertOperation);
        }
    }
}
